/**
 * 作业相关API配置
 */

// API基础配置
const HOMEWORK_API_CONFIG = {
  // 后端服务地址
  BASE_URL: 'http://localhost:9100',
  // 请求超时时间
  TIMEOUT: 10000
}

/**
 * 作业相关API
 */
export const homeworkAPI = {
  // 获取作业列表
  getHomeworkList: (params) => {
    return new Promise((resolve, reject) => {
      const url = `${HOMEWORK_API_CONFIG.BASE_URL}/api/homework/class/${params.classId}`;
      const data = {
        page: params.page || 0,
        size: params.size || 10,
        sortBy: params.sortBy || 'createTime',
        sortDir: params.sortDir || 'desc'
      };
      
      uni.request({
        url: url,
        method: 'GET',
        data: data,
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200 && response.data.code === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '请求失败'));
          }
        },
        fail: (error) => {
          console.error('作业列表请求失败:', error);
          reject(error);
        }
      });
    });
  },
  
  // 获取作业详情
  getHomeworkDetail: (id) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${HOMEWORK_API_CONFIG.BASE_URL}/api/homework/${id}`,
        method: 'GET',
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200 && response.data.code === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '请求失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
}

/**
 * 作业提交相关API
 */
export const homeworkSubmitAPI = {
  // 提交作业
  submitHomework: (data) => {
    return new Promise((resolve, reject) => {
      // 构建表单数据
      const formData = {
        homeworkId: data.homeworkId,
        userId: data.userId,
        content: data.content || ''
      };
      
      uni.request({
        url: `${HOMEWORK_API_CONFIG.BASE_URL}/api/homework-submit`,
        method: 'POST',
        data: formData,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200 && response.data.code === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '提交失败'));
          }
        },
        fail: (error) => {
          console.error('作业提交失败:', error);
          reject(error);
        }
      });
    });
  },
  
  // 检查学生是否已提交作业
  checkStudentSubmitted: (homeworkId, userId) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${HOMEWORK_API_CONFIG.BASE_URL}/api/homework-submit/homework/${homeworkId}/user/${userId}/check`,
        method: 'GET',
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200 && response.data.code === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '检查失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  },
  
  // 获取学生的提交记录
  getStudentSubmit: (homeworkId, userId) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${HOMEWORK_API_CONFIG.BASE_URL}/api/homework-submit/homework/${homeworkId}/user/${userId}`,
        method: 'GET',
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '获取失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
}

/**
 * 文件相关API
 */
export const fileAPI = {
  // 上传文件
  uploadFile: (filePath, formData) => {
    return new Promise((resolve, reject) => {
      // 确保formData包含必需的uploaderId参数
      const uploadFormData = {
        ...formData,
        uploaderId: formData.uploaderId || formData.userId  // 如果没有uploaderId，使用userId作为默认值
      };
      
      uni.uploadFile({
        url: `${HOMEWORK_API_CONFIG.BASE_URL}/api/files/upload`,
        filePath: filePath,
        name: 'file',
        formData: uploadFormData,
        success: (response) => {
          try {
            const data = JSON.parse(response.data);
            if (response.statusCode === 200 && data.code === 200) {
              resolve(data);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (error) {
            reject(error);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
}

/**
 * 请假申请相关API
 */
export const leaveRequestAPI = {
  // 提交请假申请
  submitLeaveRequest: (data) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${HOMEWORK_API_CONFIG.BASE_URL}/api/leave-request`,
        method: 'POST',
        data: data,
        header: {
          'Content-Type': 'application/json'
        },
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200 && response.data.code === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '提交失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  },
  
  // 获取我的请假申请列表
  getMyLeaveRequests: (userId, params) => {
    return new Promise((resolve, reject) => {
      const url = `${HOMEWORK_API_CONFIG.BASE_URL}/api/leave-request/user/${userId}`;
      const data = {
        page: params.page || 0,
        size: params.size || 10,
        sortBy: params.sortBy || 'applyTime',
        sortDir: params.sortDir || 'desc'
      };
      
      uni.request({
        url: url,
        method: 'GET',
        data: data,
        timeout: HOMEWORK_API_CONFIG.TIMEOUT,
        success: (response) => {
          if (response.statusCode === 200 && response.data.code === 200) {
            resolve(response.data);
          } else {
            reject(new Error(response.data.message || '获取失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
}

export default {
  homeworkAPI,
  homeworkSubmitAPI,
  fileAPI,
  leaveRequestAPI
}
